<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								付款核销
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar :style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="供应商" prop="supplier">
									<el-select @clear="selectClear('supplier')" v-model="formData.supplier"
										@change="(value:any)=>selectChange(value,'supplier')" multiple ref="supplier"
										clearable>
										<el-option v-for="item in supplierOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="supplierOption[supplierIndex]?.color">
													<component :is="supplierOption[supplierIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{supplierOption[supplierIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="付款单" prop="payment">
									<el-select @clear="selectClear('payment')" v-model="formData.payment"
										@change="(value:any)=>selectChange(value,'payment')" multiple ref="payment"
										clearable>
										<el-option v-for="item in paymentOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="paymentOption[paymentIndex]?.color">
													<component :is="paymentOption[paymentIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{paymentOption[paymentIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="采购订单" prop="order">
									<el-select @clear="selectClear('order')" v-model="formData.order"
										@change="(value:any)=>selectChange(value,'order')" multiple ref="order"
										clearable>
										<el-option v-for="item in orderOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="orderOption[orderIndex]?.color">
													<component :is="orderOption[orderIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{orderOption[orderIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="采购明细" prop="paymentDetails">
									<el-select @clear="selectClear('paymentDetails')" v-model="formData.paymentDetails"
										@change="(value:any)=>selectChange(value,'paymentDetails')" multiple
										ref="paymentDetails" clearable>
										<el-option v-for="item in paymentDetailsOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="paymentDetailsOption[paymentDetailsIndex]?.color">
													<component :is="paymentDetailsOption[paymentDetailsIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{paymentDetailsOption[paymentDetailsIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="核销金额" prop="verificationAmount">
									<el-input placeholder="请填写" type="number" v-model="formData.verificationAmount" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="核销凭证" prop="verificationCertificate">
									<el-input type="text" clearable readonly>
										<template #prefix>
											<el-upload v-model:file-list="formData.files" action="/api/oss/policy"
												:on-success="onSuccess" :headers="{'Authorization':cookie.get('token')}"
												:limit="1">
												<el-button v-if="!formData.verificationCertificate" text :icon="UploadFilled">
													上传图片
												</el-button>
												<el-image v-else preview-teleported style="width: 30px; height: 30px;margin: 10px auto;" :src="formData.verificationCertificate" :preview-src-list="[formData.verificationCertificate]" />
											</el-upload>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="核销人" prop="verifier">
									<el-input placeholder="请填写" type="text" v-model="formData.verifier" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="核销日期" prop="verificationDate">
									<el-date-picker placeholder="请选择" style="width:100%;" v-model="formData.verificationDate"
										type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="账单明细" prop="billDetail">
									<el-select @clear="selectClear('billDetail')" v-model="formData.billDetail"
										@change="(value:any)=>selectChange(value,'billDetail')" multiple
										ref="billDetail" clearable>
										<el-option v-for="item in billDetailOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="billDetailOption[billDetailIndex]?.color">
													<component :is="billDetailOption[billDetailIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{billDetailOption[billDetailIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="应付明细" prop="payableDetail">
									<el-select @clear="selectClear('payableDetail')" v-model="formData.payableDetail"
										@change="(value:any)=>selectChange(value,'payableDetail')" multiple
										ref="payableDetail" clearable>
										<el-option v-for="item in payableDetailOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="payableDetailOption[payableDetailIndex]?.color">
													<component :is="payableDetailOption[payableDetailIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{payableDetailOption[payableDetailIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import {UploadFilled, UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete, CircleCheckFilled, Refresh, List, ShoppingBag, ShoppingCart } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import { ElMessage, FormInstance } from 'element-plus';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);

	// 表单
	const formData = ref({
		supplierId: null,//供应商
		supplier: [],
		paymentId: null,//采购付款单
		payment: [],
		orderId: null,//采购订单
		order: [],
		paymentDetailsId: null,//采购明细
		paymentDetails: [],
		verificationAmount: null,//核销金额
		verificationCertificate: null,//核销凭证
		files:[],
		verifier: null,//核销人
		verificationDate: null,//核销日期
		billDetailId: null,//账单明细
		billDetail: [],
		payableDetailId: null,//应付明细
		payableDetail: []
	});
	//验证
	const rules = reactive({
		supplier: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//供应商
		payment: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//采购付款单
		order: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//采购订单
		paymentDetails: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//采购订单明细
		verificationAmount: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销金额
		verificationCertificate: [],//核销凭证
		verifier: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销人
		verificationDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//核销日期
		billDetail: [],//账单明细
		payableDetail: []//应付明细
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//供应商
	const supplierOption = ref([]);
	const supplierIndex = ref(-1);
	const supplier = ref(null);
	//采购付款单
	const paymentOption = ref([]);
	const paymentIndex = ref(-1);
	const payment = ref(null);
	//采购订单
	const orderOption = ref([]);
	const orderIndex = ref(-1);
	const order = ref(null);
	//采购明细
	const paymentDetailsOption = ref([]);
	const paymentDetailsIndex = ref(-1);
	const paymentDetails = ref(null);
	//账单明细
	const billDetailOption = ref([]);
	const billDetailIndex = ref(-1);
	const billDetail = ref(null);
	//应付明细
	const payableDetailOption = ref([]);
	const payableDetailIndex = ref(-1);
	const payableDetail = ref(null);
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getSupplierList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.verifier = decodedToken?.username;
			//
			return true;
		}
		//
		const result = await request({
			url: '/SalesReceipt/PaymentVerificationById',
			params: {
				paymentVerificationId: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		//
		return true;
	}
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'supplier', //哪一个下拉框，根据ref
			option: supplierOption, //下拉列表选项
			indexVar: supplierIndex, //当前选中项
			idVar: 'supplierId', //当前id值
			blurRef: supplier, //ref
			fun: getBindId
		}, {
			type: 'payment', //哪一个下拉框，根据ref
			option: paymentOption, //下拉列表选项
			indexVar: paymentIndex, //当前选中项
			idVar: 'paymentId', //当前id值
			blurRef: payment, //ref
		}, {
			type: 'order', //哪一个下拉框，根据ref
			option: orderOption, //下拉列表选项
			indexVar: orderIndex, //当前选中项
			idVar: 'orderId', //当前id值
			blurRef: order, //ref
		}, {
			type: 'paymentDetails', //哪一个下拉框，根据ref
			option: paymentDetailsOption, //下拉列表选项
			indexVar: paymentDetailsIndex, //当前选中项
			idVar: 'paymentDetailsId', //当前id值
			blurRef: paymentDetails, //ref
		}, {
			type: 'billDetail', //哪一个下拉框，根据ref
			option: billDetailOption, //下拉列表选项
			indexVar: billDetailIndex, //当前选中项
			idVar: 'billDetailId', //当前id值
			blurRef: billDetail, //ref
		}, {
			type: 'payableDetail', //哪一个下拉框，根据ref
			option: payableDetailOption, //下拉列表选项
			indexVar: payableDetailIndex, //当前选中项
			idVar: 'payableDetailId', //当前id值
			blurRef: payableDetail, //ref
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//获取供应商
	const getSupplierList = async () => {
		const result = await request({
			url: '/SalesReceipt/selectProcuredSupplier'
		});
		//
		console.log('getSupplierList --->', result);
		supplierOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			supplierOption.value.push({
				label: `${item.supplierShortName}`,
				value: item.supplierId,
				icon: UserFilled,
				color: '#fa9e00'
			});
			if (formData.value.supplierId === item.supplierId) {
				formData.value.supplier = [item.supplierId];
				supplierIndex.value = key;
				//
				getBindId(item.supplierId);
			}
		});
	}
	const getBindId = async (supplierId : number) => {
		const result = await request({
			url: '/SalesReceipt/selectOrder',
			params: { supplierId }
		});
		//
		console.log('getBindId --->', result);
		//付款单
		paymentOption.value = [];
		result.data.t.payments.forEach((item : any, key : number) => {
			paymentOption.value.push({
				label: `${item.finance}`,
				value: item.purchasePaymentId,
				icon: CircleCheckFilled,
				color: '#fa9e00'
			});
			if (formData.value.paymentId === item.purchasePaymentId) {
				formData.value.payment = [item.purchasePaymentId];
				paymentIndex.value = key;
				//
			}
		});
		//采购订单
		orderOption.value = [];
		result.data.t.orders.forEach((item : any, key : number) => {
			orderOption.value.push({
				label: `${item.purchaseOrderNumber}`,
				value: item.purchaseOrderId,
				icon: ShoppingCart,
				color: '#fa9e00'
			});
			if (formData.value.orderId === item.purchaseOrderId) {
				formData.value.order = [item.purchaseOrderId];
				orderIndex.value = key;
				//
			}
			//采购明细
			paymentDetailsOption.value = [];
			item.purchaseDetails.forEach((item1 : any, key1:number) => {
				paymentDetailsOption.value.push({
					label: `${item.purchaseOrderNumber}`,
					value: item1.purchaseDetailId,
					icon: ShoppingBag,
					color: '#fa9e00'
				});
				//
				if (formData.value.paymentDetailsId === item1.purchaseDetailId) {
					formData.value.paymentDetails = [item1.purchaseDetailId];
					paymentDetailsIndex.value = key1;
					//
				}
			});
		});

		//账单明细
		billDetailOption.value = [];
		result.data.t.supplierStatements.forEach((item : any, key : number) => {
			billDetailOption.value.push({
				label: `${item.supplierStatementId}`,
				value: item.supplierStatementId,
				icon: Refresh,
				color: '#42b382'
			});
			//
			if (formData.value.billDetailId === item.supplierStatementId) {
				formData.value.billDetail = [item.supplierStatementId];
				billDetailIndex.value = key;
				//
			}
		});
		//应付明细
		payableDetailOption.value = [];
		result.data.t.payableDetails.forEach((item : any, key : number) => {
			payableDetailOption.value.push({
				label: `${item.receivablePayableDetailId}`,
				value: item.receivablePayableDetailId,
				icon: List,
				color: '#5283ff'
			});
			//
			if (formData.value.payableDetailId === item.receivablePayableDetailId) {
				formData.value.payableDetail = [item.receivablePayableDetailId];
				payableDetailIndex.value = key;
				//
			}
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value };
				delete data.billDetail;
				delete data.order;
				delete data.payableDetail;
				delete data.payment;
				delete data.paymentDetails;
				delete data.supplier;
				
				let type = '';
				if (!route.query.id) {
					type = '/savePaymentVerification';
				} else {
					type = '/updatePaymentVerification';
				}
				//
				const result = await request({
					url: '/SalesReceipt' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				// //
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//凭证上传成功
	const onSuccess = (res : any) => {
		console.log('onSuccess --->', res);
		//
		formData.value.verificationCertificate = res.t;
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}
	.el-upload-list--text {
		display: none;
	}
	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>